<template>
  <div>
    <el-collapse v-model="activeNames">
      <el-collapse-item name="info" class="padding-left-right-30">
        <template slot="title">
          <div class="font-size-18 font-weight-700 padding-left-10">基本信息</div>
        </template>
        <form-common v-if="projectFiledList.length > 0" @remoteMethod="remoteMethod" :filed-list.sync="projectFiledList" @selectChange="selectChange" ref="form" @rightBtnFn="rightBtnFn"></form-common>
      </el-collapse-item>
      <!-- 楼宇 -->
      <div class="division-line"></div>
      <el-collapse-item name="build" class="padding-left-right-30">
        <template slot="title">
          <div class="flex justify-between" style="width: 100%">
            <span class="font-size-18 font-weight-700 padding-left-10">楼宇信息</span>
            <el-button class="margin-right-10" size="mini" type="primary" plain @click.stop="addBuild" v-if="isPageEdit">新增</el-button>
          </div>
        </template>
        <el-table class="new-table-style" :data="buildList" style="width: 100%">
          <el-table-column align="left" label="楼栋名称" prop="spaceName"></el-table-column>
          <el-table-column label="操作" align="center" v-if="isPageEdit" width="120">
            <template slot-scope="scope">
              <el-button type="text" @click="deleteBuild(scope.$index)">删除</el-button>
              <!-- <el-button type="text" @click="goToBuildInfo(scope.row)">查看</el-button> -->
            </template>
          </el-table-column>
        </el-table>
      </el-collapse-item>

      <!-- 附件 -->
      <div class="division-line"></div>
      <el-collapse-item name="file" class="padding-left-right-30">
        <template slot="title">
          <div class="flex justify-between" style="width: 100%">
            <span class="font-size-18 font-weight-700 padding-left-10">相关资料</span>
            <el-button class="margin-right-10" size="mini" type="primary" plain @click.stop="uploadFn" v-if="isPageEdit">上传</el-button>
          </div>
        </template>
        <el-table class="new-table-style" :data="tileFileList" style="width: 100%">
          <el-table-column align="left" label="文件名称">
            <template slot-scope="scope">
              <el-link type="primary" :underline="false" @click="uploadLoad(scope.row.fileUrl)">{{ scope.row.fileTitle }}</el-link>
            </template>
          </el-table-column>
          <el-table-column align="left" label="文件说明" prop="remark" />
          <el-table-column label="操作" align="center" v-if="isPageEdit" width="120">
            <template slot-scope="scope">
              <el-button type="text" @click="deleteFn(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-collapse-item>
    </el-collapse>

    <!-- projectStatus 1:草稿 2:已开通 -->
    <div class="margin-top-20 margin-right-65" v-if="isPageEdit">
      <el-button size="mini" class="f-right" type="primary" @click="openSaveInfo">保存</el-button>
      <el-button size="mini" class="f-right margin-right-15" type="primary" v-if="!model.projectStatus || model.projectStatus == 1" @click="openProject">项目开通</el-button>
    </div>

    <!-- 上传 -->
    <el-dialog title="批量导入" :visible.sync="uploadDialog" width="60%" :close-on-click-modal="false" :close-on-press-escape="false">
      <div class="align-center margin-bottom-20">
        <p class="left-lable font-size-16 font-weight-600">文件说明</p>
        <el-input maxlength="200" v-model="fileExplain" placeholder="请输入" clearable></el-input>
      </div>
      <div class="flex">
        <p class="left-lable font-size-16 font-weight-600 margin-top-5">选择导入文件</p>
        <uploadFile :is-multiple="false" filed-name="file" :limit="100" :max-size="100" accept-file-type=".xlsx,.xls,.csv,.png,.jpg,.Png,.Jpg,.pdf" :file-list="fileList" @handleSuccess="handleSuccess" file-url-name="fileUrl" file-txt-name="fileTitle">
          <template v-slot:info>
            <div slot="tip" class="margin-left-10">文件大小不能超过100MB</div>
          </template>
        </uploadFile>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="uploadDialog = false">取消</el-button>
        <el-button size="small" type="primary" @click="confirmUpload">确定</el-button>
      </span>
    </el-dialog>

    <!-- 上传 -->
    <el-dialog title="楼栋信息" :visible.sync="addBuildDialog" width="60%" :close-on-click-modal="false" :close-on-press-escape="false">
      <el-form :model="projectBuildForm" label-width="80px">
        <el-form-item label="楼栋">
          <el-select v-model="projectBuildForm.buildData" placeholder="请选择楼栋">
            <el-option v-for="item in buildAllData" :key="item.spaceKey" :label="item.spaceName" :value="item"></el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="addBuildDialog = false">取消</el-button>
        <el-button size="small" type="primary" @click="addBuildConfirm">确定</el-button>
      </span>
    </el-dialog>

    <AddressBMap :mapVisible="mapDialog" v-on:mapLocationClose="mapDialog = false" v-on:mapLocationSave="mapLocationSave"></AddressBMap>
  </div>
</template>
<script>
import projectInfoApi from '../../../api/projectInfo';
import formCommon from '@g/components/form/formCommon.vue';
import { dictList, provinceList, cityList, areaList, assetPackage } from '../../../api/common';
import { projectFiledList } from '../form.js';
import AddressBMap from '@/common/components/AddressBMap';
import uploadFile from '../modules/upload.vue';
import { requestTips, askDialog } from '../../../assets/util';
import {cutFileName} from "@/common/js/utils"

export default {
  props: {},
  data() {
    return {
      activeNames: ['info', 'build', 'file'],
      mapDialog: false,
      uploadDialog: false,
      fileData: {},
      fileList: [],
      fileExplain: '',
      projectFiledList: [],
      tileFileList: [],
      currentFiledItem: {}, //表单组件中返回的信息
      percentage: 0,
      model: {projectStatus:"hide"},
      list: [],
      buildList: [],
      buildAllData: [],
      addBuildDialog: false,
      projectBuildForm: {
        buildData: ''
      }
    };
  },
  computed: {
    isPageEdit() {
      return !this.$route.query.processWorkId;
    },
  },
  mounted() {
    this.projectKey = localStorage.getItem('projectKey') || this.$route.query.projectKey
    this.getDictionary();
    this.getProvinceList();
    this.getOrgList();
    this.getAssetPackage();
    this.getInfo();
    this.getBuildList();
  },

  methods: {
    //字典
    async getDictionary() {
      let res = await dictList({
        dictType: 'land_type',
      });
      projectFiledList.forEach(item => {
        if (item.bindFieldName == 'landType') {
          item.optionList = res.rows || [];
        }
        if (!this.isPageEdit) {
          item.isDisabled = true;
        }
      });
    },
    // 获取省
    async getProvinceList() {
      let res = await provinceList({});
      this.list = res.rows || [];
      projectFiledList.forEach(item => {
        if (item.bindFieldName == 'provinceCode') {
          item.optionList = res.rows || [];
        }
      });
    },
    // 获取市
    async getCityList(provinceCode) {
      let res = await cityList({ provinceCode: provinceCode });
      projectFiledList.forEach(item => {
        if (item.bindFieldName == 'cityCode') {
          item.optionList = res.rows || [];
        }
      });
    },
    // 获取区
    async getAreaList(cityCode) {
      let res = await areaList({ cityCode: cityCode });
      projectFiledList.forEach(item => {
        if (item.bindFieldName == 'areaCode') {
          item.optionList = res.rows || [];
        }
      });
    },
    //获取资产包
    async getAssetPackage(initprojectFiledList) {
      let res = await assetPackage({
        status: 1,
      });
      if(initprojectFiledList && initprojectFiledList.length){
        initprojectFiledList.forEach(item => {
          if (item.bindFieldName == 'packageKey') {
            item.optionList = res.rows || [];
          }
        });
      }
    },
    //获取运营团队
    async getOrgList() {
      let res = await projectInfoApi.apiProjectCorrelation({
        orgProjectType: 'ziguanProject',
      });

      projectFiledList.forEach(item => {
        if (item.bindFieldName == 'organizationKey') {
          item.optionList = res.rows || [];
        }
      });
    },
    // 切换
    selectChange(data) {
      if (data.filedName == 'provinceCode') {
        this.$refs['form'].setFiledSource('cityCode', '');
        this.$refs['form'].setFiledSource('areaCode', '');
        this.projectFiledList.forEach(item => {
          if (item.bindFieldName == 'areaCode') {
            item.optionList = [];
          }
        });
        this.getCityList(data.filedVal);
      } else if (data.filedName == 'cityCode') {
        this.$refs['form'].setFiledSource('areaCode', '');
        this.getAreaList(data.filedVal);
      }
    },
    remoteMethod(val) {
      projectInfoApi.managerlist({ employeeName: val.remoteVal }).then(res => {
        if (res.success) {
          val.cbList(val.formItem.bindFieldName, res.rows);
        } else {
          val.cbList(val.formItem.bindFieldName, []);
        }
      });
    },
    //详情
    async getInfo() {
      let projectKey = localStorage.getItem("projectKey")
      let initprojectFiledList = projectFiledList;
      this.projectFiledList = [];
      let res = await projectInfoApi.apiProjectDetail({
        primaryKey:this.$route.query.projectKey || projectKey
      });
      res.startYear = new Date(res.startYear).getTime()
      
      await this.getAssetPackage(initprojectFiledList);

      this.model = res;

      this.setFiledVal(initprojectFiledList, res);
      this.getCityList(res.provinceCode);
      this.getAreaList(res.cityCode);
      this.$nextTick(() => {
        this.projectFiledList = initprojectFiledList;
      });

      this.tileFileList = res.businessAttachmentMapListDto || [];
    },

    //小区地址选择回调
    mapLocationSave(e) {
      this.currentFiledItem.cb(this.currentFiledItem.filedName, e.address);
      this.currentFiledItem.model.lng = e.longitude;
      this.currentFiledItem.model.lat = e.latitude;
      this.mapDialog = false;
    },
    //下载
    uploadLoad(url) {
      let a = document.createElement('a');
      a.style.display = 'none';
      a.href = url;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
    },
    //开通项目
    async openProject() {
      if (this.model.projectStatus == 2 || this.model.projectStatus == 3) {
        let message = this.model.projectStatus == 2 ? '项目已开通成功' : '项目开通审批中';
        this.$message.warning(message);
        return;
      }
      askDialog('确认开通项目？', async () => {
        let res = await projectInfoApi.createWorkInfo({
          projectId: this.projectKey,
        });
        requestTips(res, () => {
          this.getInfo();
        });
      });
    },
    //修改信息
    async openSaveInfo() {
      let model = this.$refs.form.validateForm();
      let paramData = Object.assign({}, model)
      if (!paramData) return;
      paramData.startYear = new Date(paramData.startYear).getFullYear()
      paramData.businessAttachment = this.tileFileList;
      paramData.primaryKey = this.model.primaryKey;
      paramData.buildingKeyList = this.buildList.map(item => item.spaceKey);

      let res = await projectInfoApi.apiProjectAdd(paramData);
      requestTips(res, () => {
        this.getInfo();
        this.getBuildList()
      });
    },

    addBuild () {
      this.projectBuildForm = {
        buildData: ''
      }

      this.getBuildData()

      this.addBuildDialog = true
    },

    addBuildConfirm () {
      this.buildList.push(this.projectBuildForm.buildData)
      this.addBuildDialog = false
    },

    async getBuildData () {
      let res = await projectInfoApi.apiAllBuildList({
        ifFilterBind: true
      });

      this.buildAllData = res.rows || []
    },
    //进度条颜色
    customColor(percentage) {
      if (percentage < 30) {
        return '#909399';
      } else if (percentage < 70) {
        return '#e6a23c';
      } else {
        return '#67c23a';
      }
    },
    // 查询项目下的楼栋
    async getBuildList () {
      let res = await projectInfoApi.apiAllBuildList({
        projectKey: this.projectKey
      });

      this.buildList = res.rows || []
    },
    // 删除楼栋关联
    deleteBuild (index) {
      askDialog('确认删除？', async () => {
        this.buildList.splice(index, 1);
      });
    },
    // 查看楼栋
    goToBuildInfo (item) {
      let menuId = this.$route.query.menuId && this.$route.query.menuId != 'undefined' ? this.$route.query.menuId : '642639771fc14b8ab146f53320e0de27'

      window.open(`/businessAssets/buildView/buildInfo?menuId=${menuId}&projectKey=${this.projectKey}&spaceKey=${item.spaceKey}`, item.spaceKey)
    },
    //上传
    uploadFn() {
      this.fileList = [];
      this.fileExplain = '';
      this.uploadDialog = true;
    },
    //加文件
    confirmUpload() {
      if (!this.fileExplain) {
        this.$message.warning('请输入说明');
        return;
      }
      if (this.fileList.length == 0) {
        this.$message.warning('请上传文件');
        return;
      }
      this.fileList[0].remark = this.fileExplain;
      this.tileFileList.push(this.fileList[0]);
      this.uploadDialog = false;
    },
    //上传成功
    handleSuccess(file, fileList) {
      let fileName = cutFileName(file.data.rows[0].originalName);
      if (file.data.rows && file.data.rows.length > 0) {
        this.fileList = [
          {
            fileId: file.data.rows[0].key,
            fileUrl: file.data.rows[0].url,
            fileTitle: fileName
          },
        ];
      } else {
        this.fileList = [];
        this.$message.error(file.data.message);
      }
    },
    //点击地图回掉
    rightBtnFn(data) {
      this.currentFiledItem = data;
      this.mapDialog = true;
    },
    //回显
    setFiledVal(list, row) {
      list.forEach(item => {
        for (let i in row) {
          if (i == item.bindFieldName) {
            item.bindFieldVal = row[i];
          }
        }

        if (item.bindFieldName == 'manager') {
          item.optionList = [{
            primaryKey: row.manager,
            employeeName: row.managerName
          }]
        }
      });
    },
    deleteFn(index) {
      askDialog('确认删除？', async () => {
        this.tileFileList.splice(index, 1);
      });
    },
  },

  components: { AddressBMap, uploadFile, formCommon },
};
</script>
<style lang="scss" scoped>
.left-lable {
  width: 120px;
}
.division-line{
  width: 100%;
  background: #f1f1f1;
  height: 10px;
  margin-bottom: 10px;
}
</style>
